//导入request.js请求工具
import request from '@/utils/request.js'
import { useTokenStore } from '@/stores/token'

//提供调用用户登录接口函数
export const userLoginService = (loginData) => {
    return request.post('/user/login', loginData)
}

//用户创建邮箱验证
export const creatingUserEmail = (data) => {
    return request.post('/user/creatingUserEmail', data)
}

//基于邮箱验证跳转链接的用户创建
export const createUser = (data) => {
    return request.post('/user/creatingUser', data)
}

//获取用户的个性化推荐
export const getUserRecommendations = () => {
    return request.get('/user/recommendation')
}

// 获取图书详情
export const getBookDetail = (bookId) => {
  return request.get(`/user/getBooksDetails/${bookId}`)
}

//获取相似图书推荐
export const getSimilarBooks = (bookId) => {
    return request.get(`/user/book/similar/${bookId}`)
}

// 提交借阅申请
export const submitBorrowRequest = (bookId) => {
  return request.post(`/user/borrow/request/${bookId}`)
}

// 添加收藏
export const addToFavorites = (bookId) => {
  return request.post(`/user/favorites/add/${bookId}`)
}

// 取消收藏
export const removeFromFavorites = (bookId) => {
  return request.delete(`/user/favorites/cancel/${bookId}`)
}

// 检查是否已收藏
export const checkIsFavorite = (bookId) => {
  return request.get(`/user/favorites/check/${bookId}`)
}

//分页获取图书的评论
export const addBookRating = (data) => {
    return request.post(`/user/bookrating`, data)
}

//获取图书的平均评分
export const averageBookRating = (bookId) => {
    return request.get(`/user/bookrating/average/${bookId}`)
}

// 添加获取图书评论的接口
export const getBookRatings = (bookId, page, pageSize) => {
  return request.post(`/user/bookrating/book/${bookId}`, {
    params: {
      page,
      pageSize
    }
  })
}

// 获取图书分类
export const getBookCategories = () => {
  return request.get('/user/categories')
}

// 根据分类和字数条件分页查询图书
export const getBooksByFilter = (data) => {
  return request.post('/user/books/filter', data)
}

// 搜索图书
export function searchBooks(params) {
  return request({
    url: '/user/books/search',
    method: 'get',
    params
  })
}

// 获取作者作品列表
export function getAuthorBooks(params) {
  return request({
    url: '/user/books/author',
    method: 'get',
    params
  })
}

/**
 * 获取排行榜数据
 * @param {Object} params 请求参数
 * @param {number} params.pageNumber 页码
 * @param {number} params.pageSize 每页数量
 * @returns {Promise<{
 *   code: number,
 *   msg: string,
 *   data: {
 *     total: number,
 *     results: Array<{
 *       id: number,
 *       title: string,
 *       author: string,
 *       category: string,
 *       wordCount: number,
 *       description: string,
 *       coverUrl: string,
 *       hotDegree: number,
 *       publishDate: string
 *     }>,
 *     number: number,
 *     size: number,
 *     offset: number,
 *     totalPage: number
 *   }
 * }>}
 */
export function getRankingList(params) {
  return request({
    url: '/user/books/hot',
    method: 'get',
    params: {
      pageNumber: params.pageNumber,
      pageSize: params.pageSize
    }
  })
}

// 用户退出登录
export const userLogout = () => {
    return request.post('/user/logout')
}

// 获取用户借阅历史
export const getUserBorrowingHistory = (data) => {
    return request.post('/user/borrowing-history', data)
}

// 申请续借
export const renewBook = (borrowHistoryId) => {
    return request.post(`/user/borrow/renew/${borrowHistoryId}`)
}

// AI聊天接口
export async function chatWithAI(prompt) {
  try {
    // 从token store获取token
    const tokenStore = useTokenStore();
    const token = tokenStore.token;
    
    if (!token) {
      throw new Error('未登录或token已过期');
    }
    
    // 构建URL，添加prompt作为查询参数
    const url = `/api/user/ai/chat?prompt=${encodeURIComponent(prompt)}`;
    
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'authentication': token
      }
    });

    if (!response.ok) {
      throw new Error(`网络响应错误: ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    return {
      reader,
      decoder,
      close: () => reader.cancel()
    };
  } catch (error) {
    console.error('AI对话请求失败:', error);
    throw error;
  }
}
